from datetime import datetime
import time
import re
from typing import Optional
from logging import getLogger

log = getLogger("service")


# =======================
# 时间转换
# =======================
def convert_time(date_str: str, time_format: str = "%Y/%m/%d %H:%M:%S") -> int:
    """
    将时间字符串转换为毫秒级时间戳。
    - 若解析失败 → 返回当前时间
    """
    try:
        dt = datetime.strptime(date_str, time_format)
        return int(dt.timestamp() * 1000)
    except Exception as e:
        log.warning(f"Failed to parse date '{date_str}' with format '{time_format}': {e}")
        return int(time.time() * 1000)


# =======================
# 正则提取工具函数
# =======================
def _extract_by_regex(text: str, pattern: str) -> Optional[str]:
    """尝试用正则从 text 中提取匹配内容。"""
    try:
        match = re.search(pattern, text)
        return match.group() if match else None
    except re.error as e:
        log.error(f"Invalid regex pattern '{pattern}': {e}")
        return None


# =======================
# 模板处理：@@ / {{regex}}
# =======================
def process_template(template_str: str, device_name: str) -> str:
    """
    模板处理：
    - '@@' → 替换为 device_name
    - '{{regex}}' → 正则提取并替换
    - 不含标记 → 返回原字符串
    """

    # 1. 处理 @@ 替换
    if "@@" in template_str:
        return template_str.replace("@@", device_name)

    # 2. 处理 {{regex}} 表达式
    match = re.search(r"{{(.*?)}}", template_str)
    if match:
        regex_pattern = match.group(1).strip()
        if regex_pattern:
            extracted = _extract_by_regex(device_name, regex_pattern)
            if extracted is not None:
                return template_str.replace(match.group(0), extracted)
            else:
                msg = f"Pattern '{regex_pattern}' did not match device_name '{device_name}'"
                log.debug(msg)
                return msg

    # 3. 不含任何标记 → 原样返回
    return template_str
